<!--
 * @Descripttion: 考卷设置
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-05-12 17:40:44
 * @LastEditTime: 2021-06-10 16:02:43
 * @FilePath: \cscec-pms-admin\src\views\partyMasses\partyStudyInfo\testPaperSetting\index.vue
-->
<template>
  <!-- 考卷设置 -->
  <base-breadcrumb class="flexMemberInfo-container">
    <a-row :gutter="10" class="page-height">
      <!-- 考卷列表 -->
      <a-col :span="6">
        <a-card class="left-wrapper page-height-tree">
          <div
            v-show="leftLoading"
            class="left-wrapper-spin"
          >
            <a-spin />
          </div>
          <!-- <title-name :title="'考卷列表'" /> -->
          <div class="left-search">
            <span>搜索：</span>
            <a-input-search
              v-model="paperSearchName"
              placeholder="请搜索"
              style="width: calc(100% - 80px);"
              @search="handlePaperSearch"
            />
          </div>
          <ul class="test-paper-list">
            <li
              v-for="(item,index) in testPaperList"
              :key="index"
              :class="{'test-paper-active':active.id === item.id,'test-paper-disabled':item.state === 0}"
              @click="active = item"
            >
              {{ item.name }}
              <span v-show="item.state === 0">(禁用)</span>
            </li>
          </ul>
          <div class="test-paper-btn">
            <a-button
              v-btnPermission="'pa_003_add_01'"
              type="primary"
              @click="handlePaperAdd"
            >
              新增
            </a-button>
            <a-button
              v-btnPermission="'pa_003_edi_02'"
              type="primary"
              @click="handlePaperEdit"
            >
              编辑
            </a-button>
            <a-button
              v-btnPermission="'pa_003_dis_03'"
              :loading="disabledLoading"
              :type="disabledText === '启用'?'primary':''"
              @click="handlePaperDisabled"
            >
              {{ disabledText }}
            </a-button>
            <a-button
              v-btnPermission="'pa_003_del_04'"
              :lodaing="deleteLoading"
              @click="handlePaperDelete"
            >
              删除
            </a-button>
          </div>
        </a-card>
      </a-col>
      <!-- 考卷列表 -->
      <a-col :span="18" class="page-height-list-wrapper">
        <!-- 搜索 -->
        <searchData
          :search-data="searchOption"
          @search="search"
        />
        <!-- 搜索 -->
        <!-- 考题列表 -->
        <a-card  class="page-height-list">
          <!-- 表格操作 -->
          <div class="table-operator">
            <title-name :title="'考题列表'" />
            <a-button
              v-btnPermission="'pa_003_add_05'"
              type="primary"
              icon="plus"
              @click="handleAdd"
            >
              添加考题
            </a-button>
          </div>
          <!-- 表格操作 -->
          <!-- 表格统计 -->
          <div class="pub-table-select-count">
            <a-icon
              type="info-circle"
              theme="twoTone"
            />
            <span style="margin-right: 12px">
              考卷名称：<span class="totalNum">{{ active.name||'' }} </span>
              试题个数：<span class="totalNum">{{ statistics.total||0 }} </span>个
              考卷总分：<span class="totalNum">{{ statistics.points||0 }} </span>分
            </span>
          </div>
          <!-- 表格统计 -->
          <!-- 表格 -->
          <list-table
            ref="table"
            size="default"
            row-key="id"
            :columns="columns"
            :request="loadData"
            :alert="true"
            show-size-changer
            show-quick-jumper
          >
            <span
              slot="operator"
              slot-scope="text,record"
            >
              <template>
                <a
                  v-btnPermission="'pa_003_loo_07'"
                  @click="handleDetail(record)"
                >查看</a>
                <a-divider type="vertical" />
                <a
                  v-btnPermission="'pa_003_del_06'"
                  @click="handleDelete(record)"
                >删除</a>
              </template>
            </span>
          </list-table>
          <!-- 表格 -->
        </a-card>
        <!-- 考题列表 -->
      </a-col>
    </a-row>
    <!-- 考卷列表操作模态框 -->
    <paper-operate-form
      :visible.sync="paperOperateVisible"
      :data="paperOperateData"
      @refresh="handlePaperSearch"
    />
    <!-- 考卷列表操作模态框 -->
    <!-- 考题列表操作模态框 -->
    <add-form
      :visible.sync="addVisible"
      :data="addData"
      @refresh="handleRefresh"
    />
    <!-- 考题列表操作模态框 -->
    <!-- 查看考题信息 -->
    <operate-form
      :visible.sync="operateVisible"
      :data="operateData"
    />
    <!-- 查看考题信息 -->
  </base-breadcrumb>
  <!-- 考卷设置 -->
</template>
<script>
import { STable } from '@/components'
import Selector from '@/components/Select/Selector'
import PaperOperateForm from './components/PaperOperateForm'
import AddForm from './components/AddForm'
import OperateForm from '../questionBank/components/OperateForm'
import {
  queryExamPaperList,
  getExamTypeEnums,
  updateByPrimaryKeySelective,
  deleteByPrimaryKey,
  getExamPaperDetailById,
  deletePaperQuestion
} from '@/api/partyMasses/partyStudyInfo/testPaperSetting'
export default {
  name:'a'+ Date.now(),
  // name: 'TestPaperSetting',
  components: {
    STable,
    PaperOperateForm,
    AddForm,
    OperateForm
  },
  data() {
    return {
      // 左侧加载
      leftLoading: false,
      // 考卷列表
      testPaperList: [],
      // 考卷列表选择项
      active: {},
      // 考卷搜索值
      paperSearchName: '',
      // 考卷列表操作模态框框显示
      paperOperateVisible: false,
      // 考卷列表操作模态框数据
      paperOperateData: {
        type: '',
        record: {}
      },
      // 禁用加载
      disabledLoading: false,
      // 禁用启用按钮文字
      disabledText: '禁用',
      // 删除加载
      deleteLoading: false,
      // 考题搜索组件配置
      searchOption: [
        {
          name: '试题分类',
          value: 'examTypeId',
          type: 'select',
          data: [],
          attrs: {
            showSearch: true,
            optionFilterProp: 'children',
            filterOption: this.filterOption
          }
        },
        {
          name: '试题内容',
          value: 'examQuestionContent',
          type: 'input'
        },
        {
          name: '试题类型',
          type: Selector,
          valueKey: 'examQuestionType',
          selectType: '27',
          valueName: 'code',
          urlType: 'union'
        }
      ],
      // 表头
      columns: [
        {
          title: '序号',
          width: '80px',
          align: 'center',
          dataIndex:'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '试题分类',
          dataIndex: 'examTypeName',
          key: 'examTypeName',
          align: 'center'
        },
        {
          title: '试题内容',
          dataIndex: 'content',
          key: 'content'
        },
        {
          title: '试题类型',
          dataIndex: 'typeName',
          key: 'typeName',
          align: 'center'
        },
        {
          title: '分数',
          dataIndex: 'score',
          key: 'score',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'operator',
          width: '170px',
          scopedSlots: { customRender: 'operator' }
        }
      ],
      // 考题搜索参数
      searchData: {},
      // 表格共计
      statistics: {
        total: 0,
        points: 0
      },
      // 考题列表操作模态框框显示
      addVisible: false,
      // 考题列表操作模态框数据
      addData: {
        type: '',
        record: {}
      },
      // 查看考题作模态框框显示
      operateVisible: false,
      // 查看考题模态框数据
      operateData: {
        type: '',
        record: {}
      }
    }
  },
  watch: {
    active: {
      handler(newV, oldV) {
        this.handlePaperDisabledText(newV.id)
        this.search()
      }
    }
  },
  created() {
    this.getSearchData()
    this.getPaperData()
  },
  methods: {
    /**
     * @description: 获取考卷数据
     * @param {Void}
     * @return {Void}
     */
    async getPaperData() {
      this.leftLoading = true
      queryExamPaperList({
        examPaperName: this.paperSearchName
      })
        .then(({ data }) => {
          this.testPaperList = data.map((el) => {
            el.active = false
            return el
          })
          if (data.length > 0) {
            this.active = this.testPaperList[0]
            this.$refs.table.refresh(true)
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .finally(() => {
          this.leftLoading = false
        })
    },
    /**
     * @description: 搜索考卷
     * @param {Void}
     * @return {Void}
     */
    handlePaperSearch() {
      this.getPaperData()
    },
    /**
     * @description: 新增考卷
     * @param {Void}
     * @return {Void}
     */
    handlePaperAdd() {
      this.paperOperateVisible = true
      this.paperOperateData = {
        type: 'add',
        record: {}
      }
    },
    /**
     * @description: 编辑考卷
     * @param {Void}
     * @return {Void}
     */
    handlePaperEdit() {
      this.paperOperateVisible = true
      this.paperOperateData = {
        type: 'edit',
        record: this.testPaperList.find((el) => el.id === this.active.id)
      }
    },
    /**
     * @description: 修改禁用启用按钮文字
     * @param {String} id 选中项id
     * @return {Void}
     */
    handlePaperDisabledText(id) {
      this.disabledText = this.testPaperList.find((el) => el.id === id).state === 0 ? '启用' : '禁用'
    },
    /**
     * @description: 禁用考卷
     * @param {Void}
     * @return {Void}
     */
    handlePaperDisabled() {
      const { id, name, state } = this.testPaperList.find((el) => el.id === this.active.id)
      this.disabledLoading = true
      updateByPrimaryKeySelective({
        id,
        name,
        state: state === 0 ? 1 : 0
      })
        .then(({ code }) => {
          if (code === this.SUCCESS_CODE) {
            this.$message.success('操作成功')
            this.handlePaperSearch()
            this.handlePaperDisabledText(this.active.id)
          } else {
            this.$message.error('操作失败')
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('操作失败')
        })
        .finally(() => {
          this.disabledLoading = false
        })
    },
    /**
     * @description: 删除考卷
     * @param {Void}
     * @return {Void}
     */
    handlePaperDelete() {
      this.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.deleteLoading = true
          deleteByPrimaryKey({
            id: this.active.id
          })
            .then(({ code, msg }) => {
              if (code === this.SUCCESS_CODE) {
                this.$message.success('删除成功！')
                this.handlePaperSearch()
              } else {
                this.$message.error(msg)
              }
            })
            .catch((error) => {
              console.log(error)
              this.$message.error('删除失败！')
            })
            .finally(() => {
              this.deleteLoading = false
            })
        }
      })
    },
    /**
     * @description: 试题分类搜索
     * @param {String} input
     * @param {Object} option
     * @return {Boolean} 是否满足搜索条件
     */
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * @description: 考题搜索
     * @param {Object} value 搜索数据
     * @return {Void}
     */
    search(value) {
      this.searchData = value || {}
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 表格数据加载方法
     * @param {Object} parameter 分页信息
     * @return {Promise} 接口Promise
     */
    async loadData(parameter) {
      try {
        const params = Object.assign({}, parameter, { query: this.searchData })
        if (this.active.id) {
          params.query.examPaperId = this.active.id
        } else {
          return Promise.reject()
        }
        const { data, currentPage, totalSize, totalScore,code} = await getExamPaperDetailById(params)
        this.statistics.total = totalSize
        this.statistics.points = totalScore
        return Promise.resolve({
          data,
          code,
          currentPage,
          totalSize
        })
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    },
    /**
     * @description: 获取搜索依赖数据
     * @param {Void}
     * @return {Promise} 接口Promise
     */
    async getSearchData() {
      try {
        // [试题分类列表]
        Promise.all([getExamTypeEnums()]).then((res) => {
          this.searchOption[0].data = Object.keys(res[0].data).map((el) => {
            return {
              value: el,
              label: res[0].data[el]
            }
          })
        })
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    },
    /**
     * @description: 新增考题
     * @param {*}
     * @return {*}
     */
    handleAdd() {
      this.addVisible = true
      this.addData = {
        record: this.active,
        list: {
          examTypeId: this.searchOption[0].data
        }
      }
    },
    /**
     * @description: 查看考题
     * @param {Void}
     * @return {Void}
     */
    handleDetail(record) {
      this.operateVisible = true
      this.operateData = {
        type: 'detail',
        record,
        notype: true,
        list: {
          examTypeId: this.searchOption[0].data,
          state: [
            {
              name: '不可用',
              value: 0
            },
            {
              name: '可用',
              value: 1
            }
          ]
        }
      }
    },
    /**
     * @description: 删除考题
     * @param {Object} record 当前行数据
     * @return {Void}
     */
    handleDelete(record) {
      this.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          deletePaperQuestion({
            id: this.active.id,
            questionIds: [record.id]
          })
            .then(({ code }) => {
              if (code === this.SUCCESS_CODE) {
                this.$message.success('删除成功！')
                this.$refs.table.refresh(true)
              } else {
                this.$message.error('删除失败！')
              }
            })
            .catch((error) => {
              console.log(error)
              this.$message.error('删除失败！')
            })
        }
      })
    },
    /**
     * @description: 刷新列表
     * @param {Void}
     * @return {Void}
     */
    handleRefresh() {
      this.search()
    }
  }
}
</script>
<style lang="less" scoped>
.left-search {
  display: flex;
  span {
    width: 80px;
  }
}
.left-wrapper {
  position: relative;
}
.left-wrapper-spin {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.5);
  left: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.test-paper-list {
  height: 100%;
  // height: 500px;
  padding: 8px 5px;
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
  overflow-y: auto;
  li {
    height: 58px;
    box-shadow: 3px 2px 20px #ebebeb;
    border-radius: 4px;
    text-align: center;
    background: rgb(242, 242, 242);
    border: 1px solid #e8e8e8;
    margin: 8px 0;
    font-size: 16px;
    line-height: 58px;
    cursor: pointer;
  }
  .test-paper-active {
    color: #fff;
    background-color: #387FC6;
    border-color: #0089d0;
    box-shadow: 3px 2px 20px #ebebeb;
  }
  .test-paper-disabled {
    color: #ec808d;
  }
}
.test-paper-btn {
  display: flex;
  flex-wrap: wrap;
  button {
    margin: 5px;
  }
}
</style>
